import React, { useState, useEffect, useMemo, useRef, ElementRef } from 'react';
import {
	// useNavigate,
	useParams,
	useSearchParams,
	// unstable_useBlocker as useBlocker,
	// unstable_usePrompt as usePrompt,
} from 'react-router-dom';
import { Container, Button, Tabs, notification } from '@block/plug';
import { $fetch } from '@block/utils';
import { AuditProjPermCode, ProjectStatus } from '@src/utils';
import { UnusualPage } from '@src/components';
import ProjectDetailReport from '../project-detail-report';
import { PROJECT_STEPS_TABS } from './constant';
import './index.scss';
import Url from './url';

const { TabPane } = Tabs;
const { Header, Main } = Container;

/**
 * 审计项目管理详情
 */

const ProjectDetail = () => {
	const urlParams = useParams<{ id: string }>();
	// const navigate = useNavigate();
	const [searchParams, setSearchParams] = useSearchParams();

	const [projectData, setProjectData] = useState<AuditProjectDetailData>(); // 项目详情数据
	const [tabsList, setTabsList] = useState<SelectOption[]>(); // Tabs列表
	const [activeKey, setActive] = useState<string>('REPORT'); // 当前选中Tab
	const [reportPageMode, setReportPageMode] = useState<PageMode>(searchParams.get('reportMode') as PageMode); // 项目报告页面状态
	const [btnLoading, setBtnLoading] = useState(false); // 右上角按钮请求loading态
	const [permissionsPage, setPermissionsPage] = useState(false); // 无权限时显示页面

	const reportRef = useRef<ElementRef<typeof ProjectDetailReport>>();

	/** 租户ID */
	const tenantId = window.localStorage.getItem('tenantId') || 'MT_INTERNAL_AUDIT';

	/** 项目编号 */
	const itemNo = useMemo(() => {
		return urlParams?.id;
	}, [urlParams?.id]);

	const getReportPageMode = (projectStatus: ProjectStatus) => {
		let reportPageModeData: PageMode = 'view';
		const reportMode = searchParams.get('reportMode');
		if (reportMode === 'create' && [ProjectStatus.toBeCreate].includes(projectStatus)) {
			reportPageModeData = 'create';
		} else if (reportMode === 'edit' && [ProjectStatus.toBeSubmit, ProjectStatus.rejected].includes(projectStatus)) {
			reportPageModeData = 'edit';
		}

		setReportPageMode(reportPageModeData);
	};

	/** 获取项目详情 */
	const getProjectData = async () => {
		try {
			const res = await $fetch<AuditProjectDetailData>(Url.getProjectDetail, { itemNo, tenantId });
			setProjectData(res);
			setTabsList(PROJECT_STEPS_TABS[res?.projectStep]?.tabs);
			setActive(searchParams.get('tabsName') ?? 'REPORT'); // TODO：目前只有项目报告一个有效Tabs
			getReportPageMode(res.projectStatus);
		} catch (error) {
			if (error?.errorCode === 10001) {
				setPermissionsPage(true);
			}
			throw error;
		}
	};

	const handleBack = () => {
		window.location.href = '/audit/project/list';
	};

	/** 审计报告预览 */
	const handleReportPreview = () => {
		window.open(`/aud-sys/project/report/preview/${projectData?.itemNo}?talentId=${projectData?.tenantId}`);
	};

	/** 发送本人 */
	const handleSendMe = async (e: MouseEvent, btn: Button) => {
		try {
			btn.loading(true);
			const res = await $fetch(Url.sendMe, { itemNo: projectData?.itemNo, tenantId: projectData?.tenantId });
			notification.success({
				title: '成功',
				message: res?.message || '发送成功',
			});
		} finally {
			btn.loading(false);
		}
	};

	/** 审计报告编辑切换 */
	const handleReportMode = (mode: PageMode) => {
		if (mode === 'view') {
			searchParams.delete('reportMode');
			getProjectData();
		} else {
			searchParams.set('reportMode', mode);
			setReportPageMode(mode);
		}
		setSearchParams(searchParams);
	};

	/** 审计报告取消编辑 */
	const handleReportCancel = () => {
		reportRef.current?.cancel(() => {
			handleReportMode('view');
		});
	};

	/** 审计报告保存草稿 */
	const handleReportSaveDraft = () => {
		reportRef.current?.saveDraft(() => {
			handleReportMode('view');
		});
	};

	/** 审计报告保存并提交 */
	const handleReportSaveSubmit = () => {
		reportRef.current?.saveSubmit(() => {
			handleReportMode('view');
		});
	};

	/** 审计报告审批 */
	const handleReportApprove = () => {
		if (projectData?.bpmUrl) {
			window.open(projectData?.bpmUrl);
		}
	};
	/** 审计报告提交 */
	const handleReportSubmit = async () => {
		const res = await $fetch(Url.reportSubmit, { itemNo, tenantId });
		if (res) notification.success({ title: '成功', message: res?.message || '提交成功' });
	};

	/**
	 * Tabs切换
	 * @param key 目标activeKey
	 */
	const handleTabsChange = (key: string) => {
		if (key !== 'REPORT') {
			reportRef.current?.cancel(() => {
				window.location.replace(`/audit/project/list?openProjectDrawer=true&tabName=${key}&itemNo=${itemNo}`);
			});
		}
	};

	useEffect(() => {
		getProjectData();
	}, []);

	const renderHeaderBtns = () => {
		const { actions } = projectData ?? {};
		if (activeKey === 'REPORT') {
			if (['create', 'edit'].includes(reportPageMode)) {
				return (
					<>
						<Button disabled={btnLoading} onClick={handleReportCancel}>
							取消
						</Button>
						<Button type="primary" loading={btnLoading} onClick={handleReportSaveDraft}>
							保存草稿
						</Button>
						{actions?.includes(AuditProjPermCode.submit) && (
							<Button type="primary" loading={btnLoading} onClick={handleReportSaveSubmit}>
								保存并提交审批
							</Button>
						)}
					</>
				);
			}
			return (
				<>
					<Button onClick={handleSendMe}>发送本人</Button>
					<Button onClick={handleReportPreview}>预览</Button>
					{(actions?.includes(AuditProjPermCode.edit) || actions?.includes(AuditProjPermCode.create)) && (
						<Button
							type="primary"
							onClick={() => {
								handleReportMode(projectData?.projectStatus === ProjectStatus.toBeCreate ? 'create' : 'edit');
							}}
						>
							编辑
						</Button>
					)}
					{actions?.includes(AuditProjPermCode.submit) && (
						<Button type="primary" onClick={handleReportSubmit}>
							提交审批
						</Button>
					)}
					{actions?.includes(AuditProjPermCode.approvalView) && (
						<Button type="primary" onClick={handleReportApprove}>
							查看审批进度
						</Button>
					)}
					{actions?.includes(AuditProjPermCode.approval) && (
						<Button type="primary" onClick={handleReportApprove}>
							去审批
						</Button>
					)}
				</>
			);
		}
		return null;
	};

	const renderTabsContent = () => {
		switch (activeKey) {
			case 'REPORT': {
				return (
					<ProjectDetailReport
						ref={reportRef}
						projectData={projectData}
						pageMode={reportPageMode}
						setBtnLoading={setBtnLoading}
						handleReportMode={handleReportMode}
					/>
				);
			}
			default:
				return null;
		}
	};

	return (
		<>
			{permissionsPage ? (
				<UnusualPage tips="暂无浏览权限" detail="还没有浏览权限，联系下管理员吧！" type="noPermission" />
			) : (
				<div className="project-detail">
					<Header className="project-detail-header" height={94}>
						<div className="header">
							<div className="header-title">
								<span>
									<Button className="back-icon" icon="arrow-left" shape="circle" hoverShape onClick={handleBack} />
									审计项目名称：{projectData?.projectName || '-'}
								</span>
							</div>
							<div className="header-btns">{renderHeaderBtns()}</div>
						</div>
						<div className="sub-title">项目ID：{itemNo || '-'}</div>
					</Header>
					<Main className="project-detail-content">
						<Tabs className="project-detail-content-tabs" activeKey={activeKey} onChange={handleTabsChange}>
							{tabsList?.map((tab) => (
								<TabPane label={tab?.name} key={tab?.code} />
							))}
						</Tabs>
						{renderTabsContent()}
					</Main>
				</div>
			)}
		</>
	);
};

export default ProjectDetail;
